/**
 * Copyright 2010-present Facebook.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.twodstar.selfie;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.actionbarsherlock.app.SherlockFragment;
import com.facebook.*;
import com.facebook.internal.Utility;
import com.facebook.model.GraphObject;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseFacebookUtils;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Fragment that represents the main selection screen for Scrumptious.
 */
public class Fragment_Battles extends SherlockFragment 
{
	
	private static Fragment_Battles m_Inst;
	private static int MINIMUM_BATTLE_TOSHOW = 7;
	
	private static final int REAUTH_ACTIVITY_CODE = 100;
	private static final String PERMISSION = "publish_actions";
	    
	private static final int REFRESH_RATE_LIKE = 30;	// 30 seconds
	private static int		 m_RefershCounterLikeCount = REFRESH_RATE_LIKE;
	
	private static final int REFRESH_RATE_BATTLE = 300;	// 5 mintues
	private static int		 m_RefershCounterBattle = REFRESH_RATE_BATTLE;
	
	private boolean   m_IsFBLikeQueryFinish = false;
	private boolean m_RefreshingLike = false;
	 
    private ListView m_ListView;
    private List<Element_BattleList> m_ListElements;
    
    private ListView m_ListViewFinishedBattles;
    private List<Element_BattleList> m_listElementsFinishedBattle;
    
    private ProgressDialog progressDialog;
    private Uri photoUri;
    private String m_CounterAttackPhotoID = "";
    private boolean pendingAnnounce = false;
    
    private LinearLayout m_FrameListViews;
    private TextView	m_TxtLoading;
    private Timer m_Timer = null;
    private Pair<File, Integer> fileAndMinDimemsion;
    
   

    public static Fragment_Battles Instance()
    {
    	if(m_Inst ==  null)
    		m_Inst = new Fragment_Battles();
    	
    	return m_Inst;
    }

    
    public void Reset()
    {
    	pendingAnnounce = false;
    	m_IsFBLikeQueryFinish = false;
    	m_RefreshingLike = false;
    }
    
    private void tokenUpdated() 
    {
        if (pendingAnnounce) 
        {
            UploadPhotoToFB();
        }
    }
    
       
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        PBUtility.LOG("BattleFragment on create");
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.battles, container, false);
       
        m_ListView = (ListView) view.findViewById(R.id.battle_list);
        m_ListViewFinishedBattles = (ListView) view.findViewById(R.id.battle_Recentlist);
        init(savedInstanceState);
        
        Button ButtonNewBattle =(Button) view.findViewById(R.id.btnNewBattle);
        ButtonNewBattle.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View view) 
            {                
            	ShowFragmentCreateNewBattle();
            }
        });
        
        
        m_FrameListViews = (LinearLayout) view.findViewById(R.id.FrameListViews); 
        m_TxtLoading = (TextView) view.findViewById(R.id.txtLoading);
        
        if(m_FrameListViews != null)
        {	
        	m_FrameListViews.setVisibility(View.GONE);
        }

        return view;
    }

    private void ShowFragmentCreateNewBattle() 
	{
		//Intent intent = new Intent(this, UserDetailsActivity.class);
		//startActivity(intent);		
		MainActivity Act = (MainActivity)getActivity();
		if(Act != null)
			Act.ShowSelection();
		
	}

   
    public void onSessionStateChange(final Session session, SessionState state, Exception exception) 
    {
        if (session != null && session.isOpened()) 
        {
            if (state.equals(SessionState.OPENED_TOKEN_UPDATED)) 
            {
                tokenUpdated();
            } 
           
        } 
        else 
        {
            
        }
    }
    
    
    

  
    /**
     * Resets the view to the initial defaults.
     */
    private void init(Bundle savedInstanceState) 
    {
    	
    	m_IsFBLikeQueryFinish = false;
    	

        //listElements.add(new EatListElement(0));
        //listElements.add(new LocationListElement(1));
      
        //listElements.add(new PhotoListElement(0));
    	RefreshBattleList();
        
            
    
    }
    
    public void Tick()
    {
    	m_RefershCounterBattle--;
    	m_RefershCounterLikeCount--;
    	
    	if( m_RefershCounterBattle < -1  )
    		m_RefershCounterBattle = 2;
    	
    	if( m_RefershCounterLikeCount < -1)
    		m_RefershCounterLikeCount = 2;
    	
    	if(getActivity() == null)
    		return;
    	
    	if( MainActivity.IsOnbackground()  )
    		return;
    	
    	Fragment F = ((MainActivity)getActivity()).GetActiveFragment();
    	
    	if(F == null)
    		return;
    	
    	if(F instanceof Fragment_Battles)
    	{}else
    	{
    		return;
    	}
    	    	 	
    	if(m_ListElements != null && m_IsFBLikeQueryFinish)
    	{
    		
        	for(int i = 0; i < m_ListElements.size(); i++)
        	{
        		
        		Element_BattleList listElement = m_ListElements.get(i);
        		if (listElement != null) 
        		{
        			
        			listElement.Tick();
        		}
        	}
    	}
    	
    	
    	if(m_RefershCounterBattle < 0)
    	{
    		m_RefershCounterBattle = REFRESH_RATE_BATTLE;
    		m_RefershCounterLikeCount = REFRESH_RATE_LIKE;
    		
    		if(SelfieBattleApplication.Instance().isOnline())
    			RefreshBattleList();
    	}
    	
    	//Log.i("game","m_RefershLikeCountCounter " + m_RefershLikeCountCounter);
    	
    	if(m_RefershCounterLikeCount < 0)
    	{
    		m_RefershCounterLikeCount = REFRESH_RATE_LIKE;
    		if(SelfieBattleApplication.Instance().isOnline())
    			RefershLikeCount();
    	}
    	
    	
    }
    
   
    
    public void RefreshBattleList()
    {   
    	
    	GetBattleListAfterGettingFrdList();  
    	m_RefershCounterBattle = REFRESH_RATE_BATTLE;
    }
    
    public void GetBattleListAfterGettingFrdList()
    {
    	SelfieBattleApplication app = SelfieBattleApplication.Instance();
    	boolean IsAlreadyInitFrdList = app.GetIsAlreadyInitFrdUIDs();
    	
    	if(IsAlreadyInitFrdList )
        {
    		GetMyBattleList();    		
    		return;
        }
    	
    	if( m_Timer == null)
        {
		    final Handler handler = new Handler();
		    m_Timer = new Timer(false);
		    TimerTask timerTask = new TimerTask() 
		    {
		        @Override
		        public void run() {
		            handler.post(new Runnable() 
		            {
		                @Override
		                public void run() 
		                {
		                	WaitTick();                    		
		                }
		            });
		        }
		    };
		    m_Timer.scheduleAtFixedRate(timerTask, 0, 1000);
        }
    }
    
    private void WaitTick()
    {
    	//PBUtility.LOG("------------------------$$$----------------------");
    	
    	SelfieBattleApplication app = SelfieBattleApplication.Instance();
    	boolean IsAlreadyInitFrdList = app.GetIsAlreadyInitFrdUIDs();
    	
    	if(IsAlreadyInitFrdList )
        {
    		m_Timer.cancel();
        	m_Timer = null;
        	
        	GetMyBattleList();      
        }
    }
    
    private void ClearCurrnetBattleList()
    {
    	if(m_ListElements != null)
    	{
	    	for(int i = 0; i < m_ListElements.size(); i++)
	    	{
	    		Element_BattleList listElement = m_ListElements.get(i);
	    		if (listElement != null) 
	    		{    			
	    			BattleListAdapter BA = (BattleListAdapter)listElement.getAdapter();
	    			if(BA != null)
	    				BA.clear();
	    		}
	    	}
    	}
    }   
    
    private void ClearFinishedBattleList()
    {
    	if(m_listElementsFinishedBattle != null)
    	{
	    	for(int i = 0; i < m_listElementsFinishedBattle.size(); i++)
	    	{
	    		Element_BattleList listElement = m_listElementsFinishedBattle.get(i);
	    		if (listElement != null) 
	    		{    			
	    			BattleListAdapter BA = (BattleListAdapter)listElement.getAdapter();
	    			if(BA != null)
	    				BA.clear();
	    		}
	    	}
    	}
    }   
    

    private class BattleListAdapter extends ArrayAdapter<Element_BattleList> 
    {
        private List<Element_BattleList> listElements;

        public BattleListAdapter(Context context, int resourceId, List<Element_BattleList> listElements) 
        {
            super(context, resourceId, listElements);
            
            this.listElements = listElements;
            for (int i = 0; i < listElements.size(); i++) 
            {
                listElements.get(i).setAdapter(this);
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) 
        {
        	Element_BattleList listElement = listElements.get(position);
        	/*
        	
        	if (listElement != null)
        	{
        		if(listElement.GetIsAlreadySetView())
        			return convertView;
        	}
        	*/
        	
        	PBUtility.LOG("CALLING GETVIEW");
            
        	
            View view = convertView;
            if (view == null) 
            {
                LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.battlelistitem, null);
            }

            if (listElement != null) 
            {            
                
               
                TextView text1 = (TextView) view.findViewById(R.id.battle_playername1);
                TextView text2 = (TextView) view.findViewById(R.id.battle_playername2);
                
                text1.setText(listElement.getPlayerName1());
                text2.setText(listElement.getPlayerName2());
                
                ImageView ImageViewLeft = (ImageView)view.findViewById(R.id.icon_p1);
                ImageView ImageViewRight = (ImageView)view.findViewById(R.id.icon_p2);
                
                ImageViewLeft.setOnClickListener(listElement.getOnClickListenerLeft());
                ImageViewRight.setOnClickListener(listElement.getOnClickListenerRight());
                       
                listElement.LoadImageFromURL(ImageViewLeft,  true);
                listElement.LoadImageFromURL(ImageViewRight, false);
                
                ProgressBar PB = (ProgressBar)view.findViewById(R.id.progressBar1);
                PB.setProgress(30);
                
                TextView TextView_TotalLike1 = (TextView) view.findViewById(R.id.LikeTotal1);;
                TextView TextView_TotalLike2 = (TextView) view.findViewById(R.id.LikeTotal2);;
                TextView TextView_BattleLike1 = (TextView) view.findViewById(R.id.LikeBattle1);
                TextView TextView_BattleLike2 = (TextView) view.findViewById(R.id.LikeBattle2);
                TextView TextView_CountDown = (TextView) view.findViewById(R.id.BattleCountDown);  
                Button BtnCounterAttack = (Button) view.findViewById(R.id.btnCounterAttack);
                ImageView	ImgOfficial = (ImageView) view.findViewById(R.id.imgOfficial);
                
                if(TextView_CountDown != null)
                	TextView_CountDown.setVisibility(View.GONE);
                if(TextView_TotalLike1 != null)
                	TextView_TotalLike1.setVisibility(View.GONE);
                if(TextView_TotalLike2 != null)
                	TextView_TotalLike2.setVisibility(View.GONE);
                if(TextView_BattleLike1 != null)
                	TextView_BattleLike1.setVisibility(View.GONE);
                if(TextView_BattleLike2 != null)
                	TextView_BattleLike2.setVisibility(View.GONE);
                
                if(PB != null)
                	PB.setVisibility(View.GONE);
                
                if(BtnCounterAttack != null)
                	BtnCounterAttack.setVisibility(View.GONE);
                
                	
                               
                listElement.SetViewElements(TextView_TotalLike1, TextView_TotalLike2, 
                							TextView_BattleLike1, TextView_BattleLike2, TextView_CountDown, 
                							PB, BtnCounterAttack, ImgOfficial);
                
                
            }
            return view;
        }

    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
    	// TODO Auto-generated method stub
    	super.onActivityResult(requestCode, resultCode, data);
    	PBUtility.LOG(" request code " + requestCode);
    	
    	Uri tempUri = Element_BattleList.GetResultURI();
        if (tempUri != null) 
        {
            photoUri = tempUri;
        } 
        else if (data != null) 
        {
            photoUri = data.getData();
        }

        if(photoUri != null)
        	handleAnnounce();
    }
    
    private void ShowWhatIAmDoing(String Msg)
    {
    	
    	if(getActivity() != null)
    	{
    		MainActivity Act = (MainActivity)getActivity();
    		
    		if(Msg.isEmpty())
    		{
    			
    			Act.getSupportActionBar().setDisplayShowTitleEnabled(false);
    		}
    		else
    		{
    			Act.getSupportActionBar().setDisplayShowTitleEnabled(true);
    			Act.setTitle(Msg);    			
    		}
    		
    	}
    }
    
    private void GetMyBattleList()
    {
    	ParseQuery<ParseObject> Q1 = ParseQuery.getQuery("Battles");
    	Q1.whereEqualTo("P1", SelfieBattleApplication.Instance().GetFBID() );    	
    	
    	ParseQuery<ParseObject> Q2 = ParseQuery.getQuery("Battles");
    	Q2.whereEqualTo("P2", SelfieBattleApplication.Instance().GetFBID() );    	
    	
    	 
    	List<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>();
    	queries.add(Q1);
    	queries.add(Q2);
    
    	 
    	ParseQuery<ParseObject> mainQuery = ParseQuery.or(queries);
    	mainQuery.whereEqualTo("WinnerID", "0");
    	mainQuery.orderByDescending("StartDate");
    	mainQuery.setLimit(30);    	
    	
    	
    	ShowWhatIAmDoing("Loading My Battles");
    	
    	mainQuery.findInBackground(new FindCallback<ParseObject>() 
    	{
    	  
    	  public void done(List<ParseObject> results, ParseException e) 
    	  {
    		    	
    		  if(e == null)
    		  {
    			  	if(m_TxtLoading != null)
  			  		m_TxtLoading.setVisibility(View.GONE);
  			  	
  			  	 	if(m_FrameListViews != null)
  			        {	
  			        	m_FrameListViews.setVisibility(View.VISIBLE);
  			        }
  			  	 
    			    // clear old list before updating with new data from Parse
    			  	ClearCurrnetBattleList();  
    		  	    		  
    			  	m_ListElements = new ArrayList<Element_BattleList>();  	        
	    	        
	    	        //  Add Player's Battle First
	    	        for(int i = 0; i < results.size(); i++)
	    	        {        	
	    	        	ParseObject Obj = results.get(i);	    	
	    	        	AddToListView(Obj,true);
	    	        }
	    	        
	    	         
	
	    	        if(getActivity() != null)
	    	        	m_ListView.setAdapter(new BattleListAdapter(getActivity(), R.id.battle_list, m_ListElements)); 
	    	        
    		  }
    		  GetFriBattleList(SelfieBattleApplication.Instance().GetAppFrdList());
    	  }
    	});
    }
    
    
    private void GetFriBattleList(final String[] UIDArray)
    {      	
    	    	   	
    	ParseQuery<ParseObject> Q3 = ParseQuery.getQuery("Battles");
    	Q3.whereContainedIn("P1", Arrays.asList(UIDArray));
    	Q3.whereEqualTo("WinnerID", "0"); 
    	Q3.whereGreaterThan("EndDate", SntpClient.GetTimeUTC());
    	
    	ParseQuery<ParseObject> Q4 = ParseQuery.getQuery("Battles");
    	Q4.whereContainedIn("P2", Arrays.asList(UIDArray));
    	Q4.whereEqualTo("WinnerID", "0");
    	Q4.whereGreaterThan("EndDate", SntpClient.GetTimeUTC());    	
      	 
    	List<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>();
    
    	queries.add(Q3);
    	queries.add(Q4);    	
    	 
    	ParseQuery<ParseObject> mainQuery = ParseQuery.or(queries);   	

    	mainQuery.orderByDescending("StartDate");
    	mainQuery.setLimit(30-this.m_ListElements.size());    	
    	
    	ShowWhatIAmDoing("Loading Friends Battles");
    	
    	mainQuery.findInBackground(new FindCallback<ParseObject>() 
    	{
    	  
    	  public void done(List<ParseObject> results, ParseException e) 
    	  {
    		    	
    		  if(e == null)
    		  {
    			  		    	        
	    	        // Add Other Players (friends) Battles
	    	        for(int i = 0; i < results.size(); i++)
	    	        {        	
	    	        	ParseObject Obj = results.get(i);
	    	        	AddToListView(Obj,false);    	        	
	    	        	
	    	        }
	    	        
	    	        
	
	    	        if(getActivity() != null)
	    	        	m_ListView.setAdapter(new BattleListAdapter(getActivity(), R.id.battle_list, m_ListElements));
	    	        
	    	        	
	    	        
    		  }
    		  if(m_ListElements.size() >= 30)
  	          {
  	        	GetMyBattleList();	    	        	
  	          }
  	          else
  	          {
  	        	GetOfficialBattleList(UIDArray);	    	        	
  	          }  
    	  }
    	});
    	
    }
    
    private void GetOfficialBattleList(final String[] UIDArray)
    {      	
    	    	   	
    	ParseQuery<ParseObject> Q3 = ParseQuery.getQuery("Battles");    
    	Q3.whereEqualTo("WinnerID", "0"); 
    	Q3.whereNotContainedIn("P1", Arrays.asList(UIDArray));
    	Q3.whereNotContainedIn("P2", Arrays.asList(UIDArray));
    	Q3.whereEqualTo("IsCounterAttacked", true);
    	Q3.whereGreaterThan("EndDate", SntpClient.GetTimeUTC());  
    	Q3.orderByDescending("StartDate");
    	Q3.setLimit(30-this.m_ListElements.size());    	
    	
    	ShowWhatIAmDoing("Loading Official Battles");
    	
    	Q3.findInBackground(new FindCallback<ParseObject>() 
    	{
    	  
    	  public void done(List<ParseObject> results, ParseException e) 
    	  {
    		    	
    		  if(e == null)
    		  {
    			  		    	        
	    	        // Add Other Players (friends) Battles
	    	        for(int i = 0; i < results.size(); i++)
	    	        {        	
	    	        	ParseObject Obj = results.get(i);
	    	        	AddToListView(Obj,false);    	        	
	    	        	
	    	        }
	
	    	        if(getActivity() != null)
	    	        	m_ListView.setAdapter(new BattleListAdapter(getActivity(), R.id.battle_list, m_ListElements));
	    	        
	    	          
	    	        
	    	        
    		  }
    		  
    		  if(m_ListElements.size() >= 30)
	  	      {
	  	       	GetMyBattleList();	    	        	
	  	      }
	  	      else
	  	      {
	  	        	GetOtherBattleList(UIDArray);	    	        	
	  	      }
    	  }
    	});
    	
    }
    
    private void GetOtherBattleList(String[] UIDArray)
    {      	
    	    	   	
    	ParseQuery<ParseObject> Q3 = ParseQuery.getQuery("Battles");    
    	Q3.whereEqualTo("WinnerID", "0"); 
    	Q3.whereNotContainedIn("P1", Arrays.asList(UIDArray));
    	Q3.whereNotContainedIn("P2", Arrays.asList(UIDArray));
    	Q3.whereEqualTo("IsCounterAttacked", false);
    	Q3.whereGreaterThan("EndDate", SntpClient.GetTimeUTC());  
    	Q3.orderByDescending("StartDate");
    	Q3.setLimit(30-this.m_ListElements.size());    	
    	
    	ShowWhatIAmDoing("Loading Other Battles");
    	
    	Q3.findInBackground(new FindCallback<ParseObject>() 
    	{
    	  
    	  public void done(List<ParseObject> results, ParseException e) 
    	  {
    		    	
    		  if(e == null)
    		  {
    			  		    	        
	    	        // Add Other Players (friends) Battles
	    	        for(int i = 0; i < results.size(); i++)
	    	        {        	
	    	        	ParseObject Obj = results.get(i);
	    	        	AddToListView(Obj,false);    	        	
	    	        	
	    	        }
	
	    	        if(getActivity() != null)
	    	        	m_ListView.setAdapter(new BattleListAdapter(getActivity(), R.id.battle_list, m_ListElements));
	    	        
	    	        
    		  }
    		  
    		  GetMyFinishedBattleList();
    	  }
    	  
    	  
    	});
    	
    }
    
    
    public void ForceRefreshBattleList(int Dealy)
    {
    	 
    	m_RefershCounterBattle = Dealy;    	
    }
    
    public void ForceRefreshLike(int Dealy)
    {
    	if(m_RefreshingLike == false)
    		m_RefershCounterLikeCount = Dealy;
    }
    
    
    private void AddToListView(ParseObject Obj)
    {
    	String P1 = Obj.getString("P1");
    	String P2 = Obj.getString("P2");
    	
    	m_ListElements.add(new Element_BattleList(    			
    			getActivity(),
    			m_ListView,
    			this,
    			Obj,
    			m_ListElements.size(),
				P1, 
				P2, 
				Obj.getString("Photo_URL_1"), 
				Obj.getString("Photo_URL_2"), 
				Obj.getString("PhotoID_P1"), 
				Obj.getString("PhotoID_P2"), 
				Obj.getString("Name1"), 
				Obj.getString("Name2"),
				Obj.getString("WinnerID"),
				Obj.getInt("InitialLikeCount_P2"),
				Obj.getInt("Finished_Like1"),
				Obj.getInt("Finished_Like2"),				
				Obj.getLong("StartDate"),
				Obj.getLong("EndDate"),
				Obj.getBoolean("IsCounterAttacked")
				));
    }
   
    private void AddToListView(ParseObject Obj, Boolean AddOnlyPlayerBattle)
    {
    	String P1 = Obj.getString("P1");
    	
    	SelfieBattleApplication app = SelfieBattleApplication.Instance();
    	String FBID =  app.GetFBID(); 
    	String FBID2 = Obj.getString("P2");
    	if(FBID2 == null)
    		FBID2 = "no";
    	
    	boolean ToAdd = false;
    	if(AddOnlyPlayerBattle)
    	{
    		if(P1.equalsIgnoreCase(FBID) == true || FBID2.equalsIgnoreCase(FBID) == true )
    			ToAdd = true;
    	}
    	else
    	{
    		ToAdd = true;
    		if(P1.equalsIgnoreCase(FBID) == true || FBID2.equalsIgnoreCase(FBID) == true )
    			ToAdd = false;
    	}
    	
    	if(ToAdd)
    	{
    		AddToListView(Obj);
    		
    	}
				
    }
    
    private void GetMyFinishedBattleList()
    {  
    	
    	ParseQuery<ParseObject> Q1 = ParseQuery.getQuery("Battles");
    	Q1.whereEqualTo("P1", SelfieBattleApplication.Instance().GetFBID() );    	
    	
    	ParseQuery<ParseObject> Q2 = ParseQuery.getQuery("Battles");
    	Q2.whereEqualTo("P2", SelfieBattleApplication.Instance().GetFBID() );
    	
    	//ParseQuery<ParseObject> Q3 = ParseQuery.getQuery("Battles");    	
    	 
    	List<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>();
    	queries.add(Q1);
    	queries.add(Q2);    	
    	//queries.add(Q3);
    	 
    	ParseQuery<ParseObject> mainQuery = ParseQuery.or(queries);
    	mainQuery.whereNotEqualTo("WinnerID", "0");
    	//long EndDate = SntpClient.GetTimeUTC();    	
    	mainQuery.orderByDescending("EndDate");
    	mainQuery.setLimit(5);    					
    	
    	ShowWhatIAmDoing("Loading My Battles Results");
    	
    	mainQuery.findInBackground(new FindCallback<ParseObject>() 
    	{
    	  
    	  public void done(List<ParseObject> results, ParseException e) 
    	  {
    		    	
    		  if(e == null)
    		  {
    			    // clear old list before updating with new data from Parse
    			  	ClearFinishedBattleList();  
    		  	    		  
	    	        m_listElementsFinishedBattle = new ArrayList<Element_BattleList>();  	        
	    	        
	    	        //  Add Player's Battle First
	    	        for(int i = 0; i < results.size(); i++)
	    	        {        	
	    	        	ParseObject Obj = results.get(i);	    	
	    	        	AddToFinsihedListView(Obj,true);
	    	        }
	    	        
	    	       
	    	        if(getActivity() != null)
	    	        	m_ListViewFinishedBattles.setAdapter(new BattleListAdapter(getActivity(), R.id.battle_Recentlist, m_listElementsFinishedBattle));
	    	        
	    	       
	    	       
    		  }
    		  
    		  GetFinishedFriendBattleList(SelfieBattleApplication.Instance().GetAppFrdList());
    	  }
    	});
    	
    }
    
    private void GetFinishedFriendBattleList(String[] UIDArray)
    {  
    	
    	ParseQuery<ParseObject> Q1 = ParseQuery.getQuery("Battles");
    	Q1.whereContainedIn("P1", Arrays.asList(UIDArray));    	
    	
    	ParseQuery<ParseObject> Q2 = ParseQuery.getQuery("Battles");
    	Q2.whereContainedIn("P2", Arrays.asList(UIDArray));
    	
    	//ParseQuery<ParseObject> Q3 = ParseQuery.getQuery("Battles");    	
    	 
    	List<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>();
    	queries.add(Q1);
    	queries.add(Q2);    	
    	//queries.add(Q3);
    	 
    	ParseQuery<ParseObject> mainQuery = ParseQuery.or(queries);
    	mainQuery.whereNotEqualTo("WinnerID", "0");
    	//long EndDate = SntpClient.GetTimeUTC();    	
    	mainQuery.orderByDescending("EndDate");
    	mainQuery.setLimit(MINIMUM_BATTLE_TOSHOW-m_listElementsFinishedBattle.size());    					
    	
    	ShowWhatIAmDoing("Loading My Friend Battle Results");
    	
    	mainQuery.findInBackground(new FindCallback<ParseObject>() 
    	{
    	  
    	  public void done(List<ParseObject> results, ParseException e) 
    	  {
    		    	
    		  if(e == null)
    		  {
    			   // Add Other Players (friends) Battles
	    	        for(int i = 0; i < results.size(); i++)
	    	        {        	
	    	        	ParseObject Obj = results.get(i);
	    	        	AddToFinsihedListView(Obj,false);	    	        	
	    	        	
	    	        }
	    	        	    	        
	
	    	        if(getActivity() != null)
	    	        	m_ListViewFinishedBattles.setAdapter(new BattleListAdapter(getActivity(), R.id.battle_Recentlist, m_listElementsFinishedBattle));
	    	        
	    	        
    		  }
    		  
    		   if(m_listElementsFinishedBattle.size() >= MINIMUM_BATTLE_TOSHOW)
	  	       {
	  	        	RefershLikeCount();
	  	        	PBUtility.LOG(" no extra count  " +  m_listElementsFinishedBattle.size() );
	  	       }
	  	       else
	  	       {
	  	        	GetExtraFinishedBattleList(SelfieBattleApplication.Instance().GetAppFrdList());
	  	        	PBUtility.LOG(" extra count  " +  m_listElementsFinishedBattle.size() );
	  	       }
	    	}
    	});
    	
    }
    
    public static void Recreated()
    {
   	 	m_Inst = null;
    }
    
    private void GetExtraFinishedBattleList(String[] UIDArray)
    {
    	ShowWhatIAmDoing("Loading My Other Battle Results");
    	    	
    	ParseQuery<ParseObject> Q3 = ParseQuery.getQuery("Battles");         	
    	Q3.whereNotEqualTo("WinnerID", "0");
    	//long EndDate = SntpClient.GetTimeUTC();
    	Q3.whereNotContainedIn("P1", Arrays.asList(UIDArray));
    	Q3.whereNotContainedIn("P2", Arrays.asList(UIDArray));
    	Q3.orderByDescending("EndDate");
    	Q3.setLimit(MINIMUM_BATTLE_TOSHOW - m_listElementsFinishedBattle.size());    					
    	
    	
    	Q3.findInBackground(new FindCallback<ParseObject>() 
    	{
    	  
    	  public void done(List<ParseObject> results, ParseException e) 
    	  {
    		    	
    		  if(e == null)
    		  {
    			    	    	        
	    	        // Add Other Players (friends) Battles
	    	        for(int i = 0; i < results.size(); i++)
	    	        {        	
	    	        	ParseObject Obj = results.get(i);
	    	        	AddToFinsihedListView(Obj,false);
	    	        }
	    	        	    	        
	
	    	        if(getActivity() != null)
	    	        	m_ListViewFinishedBattles.setAdapter(new BattleListAdapter(getActivity(), R.id.battle_Recentlist, m_listElementsFinishedBattle));	    	        
	    	        
	    	        
    		  }
    		  
    		  ShowWhatIAmDoing("");
    		  RefershLikeCount();
    	  }
    	});
    }
    
    
    private void AddToFinsihedListView(ParseObject Obj, Boolean AddOnlyPlayerBattle)
    {
    	// we will only accept first five record.
    	//if( m_listElementsFinishedBattle.size() >= MINIMUM_BATTLE_TOSHOW)
    	//	return;
    	
    	if(getActivity() == null)
    		return;
    		
    	
    	String P1 = Obj.getString("P1");
    	String P2 = Obj.getString("P2");
    	SelfieBattleApplication app = SelfieBattleApplication.Instance();
    	String FBID =  app.GetFBID(); 
    	
    	boolean ToAdd = false;
    	if(AddOnlyPlayerBattle)
    	{
    		if(P1.equalsIgnoreCase(FBID) == true || P1.equalsIgnoreCase(FBID) == true )
    			ToAdd = true;
    	}
    	else
    	{
    		ToAdd = true;
    		if(P1.equalsIgnoreCase(FBID) == true || P1.equalsIgnoreCase(FBID) == true )
    			ToAdd = false;
    	}
    	
    	if(ToAdd)
    	{
    		m_listElementsFinishedBattle.add(
    										new Element_BattleList(	
    											getActivity(), 
    											m_ListViewFinishedBattles,
    											this,
												Obj,
												m_listElementsFinishedBattle.size(),
												P1, 
												P2, 
												Obj.getString("Photo_URL_1"), 
												Obj.getString("Photo_URL_2"), 
												Obj.getString("PhotoID_P1"), 
												Obj.getString("PhotoID_P2"), 
												Obj.getString("Name1"), 
												Obj.getString("Name2"),
												Obj.getString("WinnerID"),
												Obj.getInt("InitialLikeCount_P2"),
												Obj.getInt("Finished_Like1"),
												Obj.getInt("Finished_Like2"),
												Obj.getLong("StartDate"),
												Obj.getLong("EndDate"),
												Obj.getBoolean("IsCounterAttacked")
												));
    	}
				
    }
    
    
    private void ShowCanClickAndLike()
    {
    	String text = getString(R.string.canclickandlike);
        Toast toast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
        toast.show();
    }
    
    private void RefershLikeCount()
    {
    	m_RefershCounterLikeCount = REFRESH_RATE_LIKE;
    	
    	int TotalCount = 0;
    	Session session = Session.getActiveSession();
        if (session != null && session.isOpened()) 
        {        
        }
        else
        {
        	return;
        }
                
        String  UID_List = "";
        
        if(m_ListElements != null)                	
        	TotalCount += m_ListElements.size();
        if(m_listElementsFinishedBattle != null)                	
        	TotalCount += m_listElementsFinishedBattle.size();
        
        String[] UIDArray = new String[TotalCount*2];
        int Index = 0;
        
        if(m_ListElements != null)
        {        	
        	for(int i = 0; i < m_ListElements.size(); i++)
	        {
	        	Element_BattleList listElement = m_ListElements.get(i);
	    		if (listElement != null) 
	    		{
	    			UIDArray[Index] = listElement.getPhotoID1();
	    			Index++;
	    			UIDArray[Index] = listElement.getPhotoID2();
	    			Index++;
	    		}        	
	        }
        }
        
        if(m_listElementsFinishedBattle != null)
        {        	
        	for(int i = 0; i < m_listElementsFinishedBattle.size(); i++)
	        {
	        	Element_BattleList listElement = m_listElementsFinishedBattle.get(i);
	    		if (listElement != null) 
	    		{
	    			UIDArray[Index] = listElement.getPhotoID1();
	    			Index++;
	    			UIDArray[Index] = listElement.getPhotoID2();	
	    			Index++;
	    		}        	
	        }
        }
        
               	
    	for(int i = 0; i < TotalCount*2; i++)
        {        	
    		if(UIDArray[i].isEmpty() == false)
    		{
				UID_List += UIDArray[i];
				if( i <  (TotalCount*2) -1 )
				{
					UID_List += ",";
				}
    		}
    		        	
        }
        
    	if(UID_List.isEmpty())
    	{
    		return;
    	}
        
        //Log.i("game", UID_List);
        
    	String fqlQuery = "SELECT object_id,like_info FROM photo WHERE object_id in ( " + UID_List + " ) ";
        Bundle params = new Bundle();
        params.putString("q", fqlQuery);
        
        PBUtility.LOG("fqlQuery" + fqlQuery);

        Request request = new Request(session, 
            "/fql", 
            params, 
            HttpMethod.GET, 
            new Request.Callback()
        { 
            public void onCompleted(Response response) 
            {
            	ShowWhatIAmDoing("");
            	ShowCanClickAndLike();
            	
            	 m_RefreshingLike = false; 
            	 m_RefershCounterLikeCount = REFRESH_RATE_LIKE;
            	 GraphObject graphObject = response.getGraphObject();               	 
               	 int LIKE_COUNT = 0;
               	 //boolean CanLike = false;
               	 
               	 if (graphObject != null) 
               	 {
                    JSONObject jsonObject = graphObject.getInnerJSONObject();                   
                    try 
                    {
                        JSONArray array = jsonObject.getJSONArray("data");
                        for (int i = 0; i < array.length(); i++) 
                        {
                            JSONObject object = (JSONObject) array.get(i);
                            String UID = object.getString("object_id");
                            JSONObject jsonObjectLIKE = object.getJSONObject("like_info");
                            LIKE_COUNT = jsonObjectLIKE.getInt("like_count");                                       
                            //CanLike = jsonObjectLIKE.getBoolean("can_like"); 
                            
                            //Log.i("game", "LIKE COUNT REFRESHING " + UID + " " + LIKE_COUNT);
                            //if(CanLike)
                            	SetLikeCount(UID, LIKE_COUNT);
                           
                            	
                            
                        }
                        
                        m_IsFBLikeQueryFinish = true;
                        if(m_ListView != null)
                        {
                        	if(m_ListView.getAdapter() != null)
                        	{
                        		//((BattleListAdapter)m_ListView.getAdapter()).notifyDataSetChanged();
                        	}
                        	
                        }
                        if(m_ListViewFinishedBattles != null)
                        {
                        	if(m_ListViewFinishedBattles.getAdapter() != null)
                        	{
                        		//((BattleListAdapter)m_ListViewFinishedBattles.getAdapter()).notifyDataSetChanged();
                        	}
                        	
                        }
                        
                   } 
                   catch (JSONException e) 
                   {
                	   e.printStackTrace();
                   }
               	 }
            }
        });
        
        Request.executeBatchAsync(request);
        ShowWhatIAmDoing("Loading LIKEs");
        m_RefreshingLike = true;     	
    }
    
    
    private void SetLikeCount(String UID, int LikeCount)
    {
    	   	
    	if(m_ListElements != null)
    	{
	    	for(int i = 0; i < m_ListElements.size(); i++)
	    	{
	    		Element_BattleList listElement = m_ListElements.get(i);
	    		if (listElement != null) 
	    		{
	    			String ID1 = listElement.getPhotoID1();
	    			String ID2 = listElement.getPhotoID2();	 			
	    			
	    			
	    			if(ID1.equalsIgnoreCase(UID))    			
	    			{
	    				listElement.SetLikeCount1(LikeCount);	    				
	    			}
	    			else if(ID2.equalsIgnoreCase(UID))
	    			{
	    				listElement.SetLikeCount2(LikeCount);	    				
	    			}
	    		}
	    	}
    	}
    	
    	if(m_listElementsFinishedBattle != null)
    	{
	    	for(int i = 0; i < m_listElementsFinishedBattle.size(); i++)
	    	{
	    		Element_BattleList listElement = m_listElementsFinishedBattle.get(i);
	    		if (listElement != null) 
	    		{
	    			String ID1 = listElement.getPhotoID1();
	    			String ID2 = listElement.getPhotoID2();	 			
	    			
	    			
	    			if(ID1.equalsIgnoreCase(UID))    			
	    			{
	    				listElement.SetLikeCount1(LikeCount);	    				
	    			}
	    			else if(ID2.equalsIgnoreCase(UID))
	    			{
	    				listElement.SetLikeCount2(LikeCount);
	    				
	    			}
	    		}
	    	}
    	}
    }   
    
    
    /*
    private void RemoveItemthatCannotLike()
    {
    	if(m_ListElements != null)
        {
    		boolean KeepLooping = true;
    		boolean IsFound = false;
    		while(KeepLooping == true)
    		{
    			IsFound = false;
	            for(int i = m_ListElements.size()-1; i >= 0; i--)
	            {
	            	Element_BattleList listElement = m_ListElements.get(i);
	        		if (listElement != null) 
	        		{
	        			if(listElement.GetCanLike1() == false || listElement.GetCanLike2() == false)
	        			{
	        				@SuppressWarnings("unchecked")
							ArrayAdapter<Element_BattleList> AD = (ArrayAdapter<Element_BattleList>) listElement.getAdapter();
	            			AD.clear();
	            			m_ListElements.remove(listElement);
	            			IsFound = true;
	            			i = -1;
	            			break;
	            		}
	        		}        	
	            }
	            if(!IsFound)
	            	KeepLooping = false;
    		}
        }
    }
    */
    
    
    private void UploadPhotoToFB() 
    {
    	Session session = ParseFacebookUtils.getSession();

        List<String> permissions = session.getPermissions();
        if (!permissions.contains(PERMISSION)) 
        {
            pendingAnnounce = true;
            if(progressDialog != null )
            {
            	progressDialog.dismiss();
            	progressDialog = null;
            }
            
            if(getActivity() != null)
            {
            	((MainActivity)getActivity()).requestPublishPermissions(session,REAUTH_ACTIVITY_CODE);
            }
           
            return;
        }
        
        // Run this in a background thread so we can process the list of responses and extract errors.
        AsyncTask<Void, Void, List<Response>> task = new AsyncTask<Void, Void, List<Response>>() 
        {
        	 @Override
        	 public void onPostExecute(List<Response> citations) 
        	 {
        		 if (fileAndMinDimemsion != null) 
        			 GetPhotoAlbumnViewURL(m_CounterAttackPhotoID);
        	 }
        	 

            @Override
            protected List<Response> doInBackground(Void... voids) 
            {
                

                RequestBatch requestBatch = new RequestBatch();

                //String photoStagingUri = null;

                if (photoUri != null) 
                {
                    try 
                    {
                        
                        
                        if (fileAndMinDimemsion != null) 
                        {
                        	// create a response callback for uploading photo
                        	Request.Callback imageCallback = new Request.Callback() 
                        	{
                        		
                                @Override
                                public void onCompleted(Response response) 
                                {
                                	                              	
                                    // Log any response error
                                    FacebookRequestError error = response.getError();
                                    if (error != null) 
                                    {                                      
                                    	PBUtility.LOG(error.getErrorMessage());
                                    	ShowCannotUploadPhoto();                                    	
                                    }
                                    else
                                    {
                                    	PBUtility.LOG(response.toString());  
                                    	
                                    	GraphObject graphObject = response.getGraphObject();
                                    	if (graphObject != null) 
               	                	 	{
	                                    	JSONObject jsonObject = graphObject.getInnerJSONObject();
	                                    	
	                                    	 try 
	            	                         {
	            	                            
	                                    		 PBUtility.LOG("id = "+ jsonObject.get("id"));	            	                               
	                                    		 m_CounterAttackPhotoID = jsonObject.get("id").toString();   
	            	                             
	            	                        } 
	            	                        catch (JSONException e) 
	            	                        {
	            	                        	e.printStackTrace();
	            	                        }	  	                        
	                                    	           		         	                        		         	       
	            	                       
               	                	 	}
            		         	        
                                    }
                                }
                            };
                        	
                            Request photoUploadRequest = Request.newUploadPhotoRequest(Session.getActiveSession(),
                                            											fileAndMinDimemsion.first, imageCallback);
                            Bundle params = photoUploadRequest.getParameters();
                            params.putString("message", "#Selfie Battle via #SelfieBattle http://goo.gl/NaDjRj");
                            
                                                       
                            photoUploadRequest.setBatchEntryName("photoUpload");
                            requestBatch.add(photoUploadRequest);                            
                          
                           
                        }
                    } 
                    catch (FileNotFoundException e) 
                    {
                    	ShowCannotUploadPhoto();
                    	return null;
                    }
                }      
              
                if (fileAndMinDimemsion == null) 
                {
                	ShowCannotUploadPhoto();
                	requestBatch.add(new Request()) ;
                }
             
                return requestBatch.executeAndWait();
            }
            

           
        };

        task.execute();
    }
    
    private void ShowCannotUploadPhoto()
    {
    	if (progressDialog != null) 
        {
            progressDialog.dismiss();
            progressDialog = null;
            
        }
    	
    	String text = getString(R.string.check_internet);
        Toast toast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
        toast.show();
    }
    
    private Pair<File, Integer> getImageFileAndMinDimension() 
    {
        File photoFile = null;
        if(photoUri == null)
        	return null;
        
        String photoUriString = photoUri.toString();
        if (photoUriString.startsWith("file://")) 
        {
            photoFile = new File(photoUri.getPath());
        } 
        else if (photoUriString.startsWith("content://")) 
        {
            String [] filePath = { MediaStore.Images.Media.DATA };
            Cursor cursor =  getActivity().getContentResolver().query(photoUri, filePath, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePath[0]);
                String filename = cursor.getString(columnIndex);
                cursor.close();

                photoFile = new File(filename);
            }
        }

        if (photoFile != null) 
        {
            InputStream is = null;
            try 
            {
                is = new FileInputStream(photoFile);

                // We only want to get the bounds of the image, rather than load the whole thing.
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(is, null, options);

                return new Pair<File, Integer>(photoFile, Math.min(options.outWidth, options.outHeight));
            } 
            catch (Exception e) 
            {
                return null;
            } 
            finally {
                Utility.closeQuietly(is);
            }
        }
        return null;
    }
    
    
    
    private void handleAnnounce() 
    {
        pendingAnnounce = false;
        Session session = ParseFacebookUtils.getSession();        
        
        if (session != null && session.isOpened())
        {
        	// Show a progress dialog because sometimes the requests can take a while.
            progressDialog = ProgressDialog.show(getActivity(), "",  getActivity().getResources().getString(R.string.progress_dialog_text), true);
	        
 	        // upload photo
            fileAndMinDimemsion = getImageFileAndMinDimension();
	        if(fileAndMinDimemsion == null)
	        {
	        	//ShowCannotCreateBattle("This photo can't be used!");
	        	return;
	        }
	        
 	        UploadPhotoToFB();   
	       
        }
    }
    
   
    
    private void GetPhotoAlbumnViewURL(String CounterAttackPhotoID)
    {    	
   
    	Session session = Session.getActiveSession();
    	
    	 if (session != null && session.isOpened())
         {}
    	 else
    	 {
    		 return;
    	 }
    	 
    	 PBUtility.LOG("Getting Albumn view " + CounterAttackPhotoID);
    	
    	String fqlQuery = "SELECT src FROM photo WHERE object_id = '" + CounterAttackPhotoID + "'";
        Bundle params = new Bundle();
        params.putString("q", fqlQuery);

        Request request = new Request(session, 
            "/fql", 
            params, 
            HttpMethod.GET, 
            new Request.Callback()
        { 
                public void onCompleted(Response response) 
                {
                	
                	 GraphObject graphObject = response.getGraphObject();
	               	 String AlbumnViewURL2 = "";	       
	               	 
	               	 if (graphObject != null) 
	               	 {
	                        JSONObject jsonObject = graphObject.getInnerJSONObject();
	                        
	                        try 
	                        {
	                            JSONArray array = jsonObject.getJSONArray("data");
	                            for (int i = 0; i < array.length(); i++) 
	                            {
	                                JSONObject object = array.getJSONObject(i);
	                                if(i == 0)
	                                {
	                                	AlbumnViewURL2 = object.get("src").toString();
	                                }	                               
	                                
	                                PBUtility.LOG(AlbumnViewURL2);	                             
	                                
	                               	 
	                            }
	                       } 
	                       catch (JSONException e) 
	                       {
	                    	   e.printStackTrace();
	                    	   if (progressDialog != null) 
                               {
                                   progressDialog.dismiss();
                                   progressDialog = null;
                               }
	                       }
	                        
	                        
	                       ParseObject PU = Element_BattleList.m_CounterAttackParseObject;	        
	                       if(PU != null)
	                       {
	                    	   DataManager.SaveCounterAttack(
		         	    		   							PU, 
		         	    		   							PU.getString("P1"), 
		         	    		   							PU.getString("Name2"), 
		         	    		   							m_CounterAttackPhotoID, 
		         	    		   							AlbumnViewURL2
		         	    		   							);
	                    	   
	                    	   HideCounterAttackButtonAfterUploading();
	                       }
		         	        
		         	       photoUri = null;		         	      
		         	        
		         	       if (progressDialog != null) 
                           {
                               progressDialog.dismiss();
                               progressDialog = null;
                           } 
		         	       
	                }
	               	else
	               	{
	               		if (progressDialog != null) 
                        {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
	               	}
                }
                
        });
        
        Request.executeBatchAsync(request);
    }
    
    
    private void HideCounterAttackButtonAfterUploading()
    {
    	if( Element_BattleList.m_CounterAttackParseObject == null)
    		return;
    	
    	Element_BattleList.m_CounterAttackParseObject = null;
    	
    	
    	if(m_ListElements != null)
    	{
    		
        	for(int i = 0; i < m_ListElements.size(); i++)
        	{
        		
        		Element_BattleList listElement = m_ListElements.get(i);
        		if (listElement != null) 
        		{
        			
        			if(listElement.getParseObj() == Element_BattleList.m_CounterAttackParseObject)
        			{
        				listElement.HideCounterAttackButton();
        			}
        		}
        	}
    	}
    }
}


